package jm.easyconfig;

import java.util.HashMap;
import java.util.Map;

import org.springframework.core.env.Environment;

public class SysProps {
	static final String APPLICATION_NODES = "easyconfig.application-nodes";

	static final ConfigItem applicationNodes = new ConfigItem();
	{
		applicationNodes.withProfile("default");
		applicationNodes.withCode(APPLICATION_NODES);
		applicationNodes.withValue("{}");
		applicationNodes.item_name = APPLICATION_NODES;
		Map<String, Object> schema = new HashMap<String, Object>();
		schema.put("type", "object");
		schema.put("$backend", true);
		applicationNodes.item_schema = schema;
		applicationNodes.updated_user = "$system";
		applicationNodes.updated_history = "{\"count\":0,\"list\":[]}";
	}

	static final String UPDATER = "easyconfig.updater";
	static final String USERS_PROP_KEY = "easyconfig.security.users";
	static final String USER_SESSION_KEY = "easyconfig-security-user";
	static final String USER_COOKIE_KEY = "easyconfig-remember-me";

	static final String CIPHER_KEYS_PROP_KEY = "easyconfig.cipher-keys";
	static final String DECRYPTED_PROPERTY_SOURCE_NAME = "easyconfig_decrypted_property_source";
	static final String DYNAMIC_PROPERTY_SOURCE_NAME = "easyconfig_dynamic_property_source";

	boolean valueEnabled = true;

	// enable the local cache in file system which is used to restore occasionally
	boolean localcacheEnabled = true;

	@EasyValue(value = "${easyconfig.localcache.enabled:true}", name = "Switch of local cache")
	public void setLocalcacheEnabled(boolean localcacheEnabled) {
		if (this.localcacheEnabled == localcacheEnabled)
			return;

		this.localcacheEnabled = localcacheEnabled;

		if (localcacheEnabled) {
			CfgContextEnvironmentAware.getSharedInstance().profilesHelper.storeLocalCache();
		} else
			CfgContextEnvironmentAware.getSharedInstance().profilesHelper.deleteLocalCache();
	}

	// Salt used to encrypt and decrypt,so if it changed,the encrypted content will
	// failed to decrypt.
	String cipherSalt = "";

	static String[] stringArrayEmpty = new String[] {};

	@EasyValue(value = "${easyconfig.item-history-max:20}", name = "Maximum change count of a property")
	int itemHistoryMax = 20;

	@EasyValue(value = "${easyconfig.change-history-max:100}", name = "Maximum change count of the whole config")
	int changeHistoryMax = 100;

	void refresh(Environment env) {
		valueEnabled = env.getProperty("easyconfig.value.enabled", boolean.class, true);

		localcacheEnabled = env.getProperty("easyconfig.localcache.enabled", Boolean.class, true);

		cipherSalt = env.getProperty("easyconfig.cipher-salt", "");

		itemHistoryMax = env.getProperty("easyconfig.item-history-max", Integer.class, 20);
		changeHistoryMax = env.getProperty("easyconfig.change-history-max", Integer.class, 100);
	}

	static final SysProps inst = new SysProps();
}